import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, DatePicker, Select, Space, Tag, Modal, message, Descriptions, Popconfirm, InputNumber, Switch } from 'antd';
import CouponFormModal from './CouponFormModal';
import CouponDetailModal from './CouponDetailModal';
import { SearchOutlined, ReloadOutlined, EyeOutlined, EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { request } from 'umi';
import { getStores, getVenues } from '@/services/store';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;

// 根据优惠券类型获取颜色
const getTypeColor = (type) => {
  const colorMap = {
    0: 'blue',
    1: 'green',
    2: 'orange',
    3: 'purple',
    4: 'red',
    5: 'cyan',
    6: 'magenta',
  };
  return colorMap[type] || 'default';
};

// 获取优惠券列表
const fetchCoupons = async (params) => {
  return request('/api/v1/coupon', {
    method: 'GET',
    params,
  });
};

// 获取优惠券详情
const fetchCouponDetail = async (id) => {
  return request(`/api/v1/coupon/${id}`, {
    method: 'GET',
  });
};

// 创建优惠券
const createCoupon = async (data) => {
  return request('/api/v1/coupon', {
    method: 'POST',
    data,
  });
};

// 更新优惠券
const updateCoupon = async (data) => {
  return request(`/api/v1/coupon/${data.id}`, {
    method: 'PUT',
    data,
  });
};

// 删除优惠券
const deleteCoupon = async (id) => {
  return request(`/api/v1/coupon/${id}`, {
    method: 'DELETE',
  });
};

const CouponList = () => {
  const [coupons, setCoupons] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [couponForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [currentCoupon, setCurrentCoupon] = useState(null);
  const [formTitle, setFormTitle] = useState('创建优惠券');
  const [processedCoupons, setProcessedCoupons] = useState([]);
  const [stores, setStores] = useState([]);
  const [venues, setVenues] = useState([]);

  // 获取优惠券列表
  const fetchCouponList = async () => {
    try {
      setLoading(true);
      const params = {
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      };
      const res = await fetchCoupons(params);
      console.log('优惠券列表数据:', res); // 添加调试日志
      if (res.success) {
        setCoupons(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total || 0,
        });
      } else {
        message.error(res.message || '获取优惠券列表失败');
      }
    } catch (error) {
      console.error('获取优惠券列表出错:', error);
      message.error('获取优惠券列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCouponList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  useEffect(() => {
    const fetchInitialData = async () => {
      try {
        const storesRes = await getStores({ page: 1, pageSize: 1000 });
        if (storesRes.success) {
          setStores(storesRes.data.list || []);
        }
        const venuesRes = await getVenues({ page: 1, pageSize: 1000 });
        if (venuesRes.success) {
          setVenues(venuesRes.data.list || []);
        }
      } catch (error) {
        console.error('Failed to fetch initial data:', error);
      }
    };
    fetchInitialData();
  }, []);

  // 处理后端返回的数据，确保时间字段正确
  useEffect(() => {
    if (coupons && coupons.length > 0) {
      setProcessedCoupons(coupons);
    } else {
      setProcessedCoupons([]);
    }
  }, [coupons]);

  // 查看优惠券详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchCouponDetail(record.id);
      console.log('优惠券详情数据:', res); // 添加调试日志
      if (res.success) {
        setCurrentCoupon(res.data);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取优惠券详情失败');
      }
    } catch (error) {
      console.error('获取优惠券详情出错:', error);
      message.error('获取优惠券详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理添加优惠券
  const handleAdd = () => {
    setFormTitle('创建优惠券');
    setCurrentCoupon(null);
    couponForm.resetFields();
    setFormVisible(true);
  };

  // 处理编辑优惠券
  const handleEdit = (record) => {
    setFormTitle('编辑优惠券');
    setCurrentCoupon(record);
    couponForm.resetFields();

    // 基础字段
    const formValues = {
      ...record,
      status: record.status === 1, // 转换为布尔值，用于Switch组件
    };

    // 根据类型设置不同字段
    switch (record.type) {
      case 0: // 折扣券
        formValues.discount = record.discount; 
        formValues.min_consume = record.min_consume; 
        break;
      case 1: // 现金券
        formValues.value = record.value;
        break;
      case 2: // 满减券
        formValues.min_consume = record.min_consume;
        formValues.value = record.value;
        break;
      case 3: // 时长券
        formValues.duration = record.duration;
        break;
      case 6: // 特价券
        formValues.value = record.value;
        break;
      default:
        break;
    }

    // 处理可用星期和时间
    if (record.available_weekdays) {
      formValues.available_weekdays = record.available_weekdays.split(',');
    }
    // 处理可用星期和时间
    if (record.available_weekdays) {
      formValues.available_weekdays = record.available_weekdays.split(',');
    }
    if (record.available_times) {
      let available_times = [];
      try {
        available_times = record.available_times
          ? JSON.parse(record.available_times).map((timeRange) => [
            moment(timeRange?.start, 'HH:mm'),
            moment(timeRange?.end, 'HH:mm'),
          ])
          : [];
      } catch (e) {
        console.log('解析可用时段失败:', e);
      }
      formValues.available_times = available_times;
    }

    couponForm.setFieldsValue(formValues);
    setFormVisible(true);
  };

  // 处理删除优惠券
  const handleDelete = async (id) => {
    try {
      setLoading(true);
      const res = await deleteCoupon(id);
      if (res.success) {
        message.success('删除优惠券成功');
        fetchCouponList();
      } else {
        message.error(res.message || '删除优惠券失败');
      }
    } catch (error) {
      console.error('删除优惠券出错:', error);
      message.error('删除优惠券失败');
    } finally {
      setLoading(false);
    }
  };

  // 提交表单
  const handleFormSubmit = async () => {
    try {
      const values = await couponForm.validateFields();
      setLoading(true);

      // 构建提交数据
      const submitData = {
        ...currentCoupon,
        id: currentCoupon ? currentCoupon.id : 0,
        name: values.name,
        type: values.type,
        status: values.status ? 1 : 0,
        valid_days: parseInt(values.valid_days),
        total_count: values.total_count || 0,
        per_limit: values.per_limit || 1,
        description: values.description || '',
      };

      console.log('提交数据:', submitData);

      // 根据类型处理不同字段
      switch (values.type) {
        case 0: // 折扣券
          submitData.discount = values.discount;
          submitData.min_consume = values.min_consume || 0;
          break;
        case 1: // 现金券
          submitData.value = values.value;
          break;
        case 2: // 满减券
          submitData.min_consume = values.min_consume;
          submitData.value = values.value;
          break;
        case 3: // 时长券
          submitData.duration = values.duration;
          break;
        case 4: // 免费券
          submitData.value = 0;
          break;
        case 5: // 赠品券
          // description is already handled
          break;
        case 6: // 特价券
          submitData.value = values.value;
          break;
        default:
          break;
      }

      // 处理可用时间和星期
      submitData.available_times = values.available_times ? JSON.stringify(values.available_times.map(t => {
        if (t) {
          return {
            start: t[0].format('HH:mm'),
            end: t[1].format('HH:mm'),
          }
        }
        return null;
      }).filter(t => t !== null)) : "";

      if (values.available_weekdays && values.available_weekdays.length > 0) {
        submitData.available_weekdays = values.available_weekdays.join(',');
      } else {
        submitData.available_weekdays = '';
      }

      // 处理适用范围
      submitData.applicable_type = values.applicable_type;
      if (values.applicable_type > 0 && values.applicable_ids) {
        submitData.applicable_ids = values.applicable_ids.join(',');
      }

      let res;
      if (currentCoupon) {
        // 更新
        res = await updateCoupon(submitData);
        console.log('更新响应:', res);
      } else {
        // 创建
        res = await createCoupon(submitData);
        console.log('创建响应:', res);
      }

      if (res.success) {
        message.success(`${currentCoupon ? '更新' : '创建'}优惠券成功`);
        setFormVisible(false);
        fetchCouponList();
      } else {
        message.error(res.message || `${currentCoupon ? '更新' : '创建'}优惠券失败`);
      }
    } catch (error) {
      console.error('表单提交错误:', error);
      message.error('表单提交失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '优惠券名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '优惠券类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => {
        const typeMap = {
          0: '折扣券',
          1: '现金券',
          2: '满减券',
          3: '时长券',
          4: '免费券',
          5: '赠品券',
          6: '特价券',
        };
        return <Tag color={getTypeColor(type)}>{typeMap[type] || '未知类型'}</Tag>;
      },
    },
    {
      title: '优惠券面值',
      dataIndex: 'value',
      key: 'value',
      render: (value, record) => {
        switch (record.type) {
          case 0: // 折扣券
            return `${record.discount}折`;
          case 1: // 现金券
          case 2: // 满减券
          case 6: // 特价券
            return `¥${record.value}`;
          case 3: // 时长券
            return `${record.duration}分钟`;
          case 4: // 免费券
            return '免费';
          case 5: // 赠品券
            return '赠品';
          default:
            return '-';
        }
      },
    },
    {
      title: '使用门槛',
      dataIndex: 'min_consume',
      key: 'min_consume',
      render: (min_consume) => {
        return min_consume > 0 ? `满${min_consume}元可用` : '无门槛';
      },
    },
    {
      title: '有效期',
      dataIndex: 'valid_days',
      key: 'valid_days',
      render: (valid_days) => `${valid_days}天`,
    },
    {
      title: '发行数量',
      dataIndex: 'total_count',
      key: 'total_count',
      render: (text) => text > 0 ? text : '不限量',
    },
    {
      title: '已领取数量',
      dataIndex: 'issued_count',
      key: 'issued_count',
    },
    {
      title: '已使用数量',
      dataIndex: 'used_count',
      key: 'used_count',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        console.log('状态值:', status, typeof status);
        return (
          <Tag color={status === 1 ? 'green' : 'red'}>
            {status === 1 ? '启用' : '禁用'}
          </Tag>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (created_at) => {
        if (created_at) {
          return moment(created_at * 1000).format('YYYY-MM-DD HH:mm:ss');
        }
        return '-';
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此优惠券吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              icon={<DeleteOutlined />}
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.name) {
      params.name = values.name;
    }
    if (values.type) {
      params.type = values.type;
    }
    if (values.status) {
      params.status = values.status;
    }
    if (values.dateRange && values.dateRange.length === 2) {
      params.startTime = values.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
      params.endTime = values.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
    }

    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1, // 重置到第一页
    });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };

  return (
    <PageContainer>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            创建优惠券
          </Button>
        </div>

        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="name" label="优惠券名称">
            <Input placeholder="请输入优惠券名称" allowClear />
          </Form.Item>
          <Form.Item name="type" label="优惠券类型">
            <Select placeholder="请选择优惠券类型" style={{ width: 150 }} allowClear>
              <Option value={0}>折扣券</Option>
              <Option value={1}>现金券</Option>
              <Option value={2}>满减券</Option>
              <Option value={3}>时长券</Option>
              <Option value={4}>免费券</Option>
              <Option value={5}>赠品券</Option>
              <Option value={6}>特价券</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" style={{ width: 150 }} allowClear>
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="创建时间">
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
        <Table
          key="id"
          columns={columns}
          dataSource={processedCoupons}
          pagination={pagination}
          onChange={handleTableChange}
          loading={loading}
        />
      </Card>
      <CouponFormModal
        visible={formVisible}
        onCancel={() => setFormVisible(false)}
        onFinish={handleFormSubmit}
        form={couponForm}
        title={formTitle}
        stores={stores}
        venues={venues}
      />
      <CouponDetailModal
        visible={detailVisible}
        onCancel={() => setDetailVisible(false)}
        coupon={currentCoupon}
      />
    </PageContainer>
  );
};
export default CouponList;